import { updateCourseActityStatus } from '@/apis/courseApi';
import { Base64 } from 'js-base64';
var app = getApp().$wepy;
// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)

export function dateFormat (date) {

  date = date.toString().replace(/-/g,'/')
  date = new Date(date);
  return formatDateByFormatString('yyyy-MM-dd', date)
}

export function dateTimeFormat (date) {
  date = date.toString().replace(/-/g,'/')
  date = new Date(date);
  return formatDateByFormatString('yyyy-MM-dd hh:mm:ss', date)
}
export function TimeFormat (date) {
  date = date.toString().replace(/-/g,'/')
  date = new Date(date);
  return formatDateByFormatString('hh:mm:ss', date)
}
export function dateTimeHMFormat (date) {
  date = date.toString().replace(/-/g,'/')
  date = new Date(date);
  return formatDateByFormatString('yyyy-MM-dd hh:mm', date)
}
export function dateFormat2 (date) {
  date = date.toString().replace(/-/g,'/')
  date = new Date(date);
  return formatDateByFormatString('yyyy/MM/dd', date)
}

export function formatDateByFormatString (fmt, date) {
  var o = {
    "M+": date.getMonth() + 1, //月份
    "d+": date.getDate(), //日
    "h+": date.getHours(), //小时
    "m+": date.getMinutes(), //分
    "s+": date.getSeconds(), //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
    "S": date.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

export function downloadFilePreview (resourceUrl) {
  app.showLoading();
  wx.downloadFile({
    url: resourceUrl,
    success: function (res) {
      const filePath = res.tempFilePath;
      wx.openDocument({
        filePath: filePath,
        success: function (res) {
          // console.log('打开文档成功');
        }
      });
    },
    complete: function (res) {
      typeof callback === 'function' && callback()
      app.hideLoading();
    }
  });
}

export function download2Save (resourceUrl) {
  app.showLoading();
  wx.downloadFile({
    url: resourceUrl,
    success: function (res) {
      const filePath = res.tempFilePath;
      wx.saveFile({
        tempFilePath: filePath,
        success (res) {
          const savedFilePath = res.savedFilePath
          console.log(savedFilePath)
        }
      })
    },
    complete: function (res) {    
      typeof callback === 'function' && callback()
      app.hideLoading();
    }
  });
}

export function playVoice (resourceUrl, callback) {
  app.showLoading();
  var bgam = wx.createInnerAudioContext();
  bgam.src = resourceUrl;
  bgam.autoplay = true
  bgam.play()
  bgam.onPlay(() => {
    app.hideLoading();
    console.log('开始播放')
  })
  bgam.onError((res) => {
    app.showError("语音播放出错")
  })
  bgam.onEnded(() => {
    app.showSuccess("播放结束")
  })
}

export function ChkCourseActivity (itemData) {

  // 活动未开始不能点，活动开始之后可以点击查看详情
  if (itemData.type == 2) {
    if (itemData.isStart == false) {
      return;
    }
  }  
  var goUrl = '';
  switch (itemData.relationType) {
    case 1100: //音频
      // playVoice(itemData.url, function () {
      // });
      goUrl = `/pages/link/index?url=${itemData.url}`;
      gotoNewPage(goUrl);
      break;
    case 1101: //视频
      goUrl = `/pages/course-activity/playVideo?id=${itemData.id}&relationId=${itemData.relationId}&url=${itemData.url}`;
      gotoNewPage(goUrl);
      break;
    case 1102: //word
    case 1103: //ppt
    case 1104: //excel
    case 1105: //pdf
      downloadFilePreview(itemData.url);
      break;
    case 1106: //图片      
      wx.previewImage({
        current: itemData.url,
        urls: [itemData.url] // 需要预览的图片http链接列表
      });
      break;
    case 1107: //其他
      download2Save(itemData.url);
      break;
    case 1200: //图文, 富文本
      goUrl = `/pages/course-activity/richText?id=${itemData.id}&relationId=${itemData.relationId}`;
      gotoNewPage(goUrl);
      break;
    case 1300: //链接    
      goUrl = `/pages/link/index?url=${itemData.url}`;
      gotoNewPage(goUrl);
      break;
    case 2000: //作业
      if (itemData.isLearn == 1) {
        return;
      }
      // itemData.url=Base64.encode(`http://localhost:6060/#/work?id=${itemData.relationId}`);
      // goUrl = `/pages/link/authPage?url=${itemData.url}`;
      
      goUrl = `/packageForCourse/pages/exercise/index?id=${itemData.relationId}&type=1&lessonId=${itemData.joinLessonId}`;

      gotoNewPage(goUrl);
      break;
    case 2001: //试卷
      goUrl = `/packageForCourse/pages/exam/index?id=${itemData.relationId}`;
      gotoNewPage(goUrl);
      break;
    case 2002: //问卷
      goUrl = `/packageForCourse/pages/survey/index?id=${itemData.relationId}`;
      gotoNewPage(goUrl);
      break;
    case 2003: //投票
      goUrl = `/pages/vote/index?id=${itemData.id}`;
      gotoNewPage(goUrl);
      break;
    case 2004: //签到
      goUrl = `/pages/course-resource-sign/index?id=${itemData.id}&relationId=${itemData.relationId}`;
      gotoNewPage(goUrl);
      break;
    case 2005: //提问
      goUrl = `/pages/course-activity/questionDisplay?id=${itemData.id}`;
      gotoNewPage(goUrl);
      break;
    case 2006: //课堂点评
      goUrl = `/pages/teacher-comment/index?id=${itemData.id}`;
      gotoNewPage(goUrl);
      break;
  }

  if (itemData.isLearn == 0) {
    updateCourseActityStatus(itemData.id)
      .then(status => {
        if (that != null) {
          //that._getCourseHoursResource()
        }
      })
      .catch(msg => {
        app.showError(msg);
      })
      .finally(() => {
        app.hideLoading();
      });
  }

}

export function getFileType (suffix) {
  var suffix = suffix.toLowerCase();
  const image = ['PNG', 'jpeg', 'jpg', 'jif', 'tiff', 'psd', 'svg'];
  const music = ['wav', 'mp3', 'ogg', 'midi', 'mp2', 'mp1', 'AAC', 'wma'];
  const video = ['wmv', 'asf', 'asx', 'rm', 'rmvb', 'mp4', '3gp', 'mov', 'm4v', 'avi', 'flv', 'dat'];
  const normal = [
    'doc',
    'docx',
    'excel',
    'link',
    'pdf',
    'ppt',
    'txt',
    'word',
    'xls',
    'xlsx',
  ];
  if (image.includes(suffix)) return 'image';
  if (music.includes(suffix)) return 'music';
  if (video.includes(suffix)) return 'video';
  if (normal.includes(suffix)) return suffix;
  return 'other';
}

export function gotoNewPage (goUrl) {
  wx.navigateTo({
    url: goUrl
  });
}

export function getActivityNameByCode (code) {
  switch (code) {
    case 1100: return "音频";
    case 1101: return "视频";
    case 1102: return "word";
    case 1103: return "ppt";
    case 1104: return "excel";
    case 1105: return "pdf";
    case 1106: return "图片";
    case 1107: return "其他";
    case 1200: return "图文";
    case 1300: return "链接";
    case 2000: return "作业";
    case 2001: return "试卷";
    case 2002: return "问卷";
    case 2003: return "投票";
    case 2004: return "签到";
    case 2005: return "提问";
    case 2006: return "课堂点评";
    default: "其他"
      break;
  }
}

export function getTeacherCommentNameByCode (code) {
  switch (code) {
    case 101: return "赞";
    case 102: return "帮助他人";
    case 103: return "成绩优异";
    case 104: return "积极思考";
    case 105: return "团队合作";
    case 106: return "认真学习";
    case 107: return "注意力集中";
    case 108: return "遵守纪律";
    case 201: return "待改进";
    case 202: return "聊天";
    case 203: return "没交作业";
    case 204: return "玩手机";
    case 205: return "追逐";
    case 206: return "走神";
    default: "其他"
      break;
  }
}

export function getQueationTypeNameByCode (code) {
  switch (code) {
    case 0: return "举手回答";
    case 1: return "在线抢答";
    case 2: return "随机抽答";
    case 5: return "点名回答";
    default: "其他"
      break;
  }
}